package logic

import (
	"MyBlogs/dao/mysql"
	"MyBlogs/models"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"sync"
	"time"
)

// 存储 WebSocket 客户端连接的集合
var clients = make(map[*websocket.Conn]models.Chat_Room)

// 保证对 clients 的并发安全访问
var clientMutex sync.Mutex

func WebSocketHandler(c *gin.Context) {
	// 升级到WebSocket连接
	ws, err := websocket.Upgrade(c.Writer, c.Request, nil, 1024, 1024)
	if err != nil {
		panic(err)
	}

	// 加入新客户端
	clientMutex.Lock()
	info := models.Chat_Room{
		UserId: 0,
	}
	clients[ws] = info
	clientMutex.Unlock()

	// 处理WebSocket消息
	go handleWebSocketMessages(ws)
}

func handleWebSocketMessages(ws *websocket.Conn) {
	for {
		messageType, p, err := ws.ReadMessage() // 阻塞等待读取客户端发送的消息
		if err != nil {
			break // 无法读取信息，退出循环
		}

		info := clients[ws]
		context := string(p)
		info.Content = context[1 : len(context)-1]
		info.CreateTime = time.Now().Format("2006-01-02 15:04:05")
		clients[ws] = info
		mysql.AddChat(&info) // 用户添加聊天记录

		broadcastMessage(ws, messageType, p) // 广播消息给所有客户端
	}

	clientMutex.Lock()
	defer clientMutex.Unlock()

	delete(clients, ws)
	ws.Close()
}

func broadcastMessage(sender *websocket.Conn, messageType int, p []byte) {
	clientMutex.Lock()
	defer clientMutex.Unlock()

	for client := range clients {
		if client != sender {
			err := client.WriteMessage(messageType, p) // 向每个客户端发送消息
			if err != nil {
				// 发送消息失败，关闭连接
				client.Close()
				delete(clients, client)
			}
		}
	}
}

// 查看所有聊天记录
func AllChats(context *gin.Context) {
	chats := mysql.AllChats()
	context.JSON(200, gin.H{
		"data": chats,
	})
}
